package com.example.demo.utils;

import com.example.demo.vo.RedisModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * redis工具类
 */
@SuppressWarnings(value = { "unchecked", "rawtypes" })
@Component
public class RedisUtil {
    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * 缓存基本的对象，Integer、String、实体类等
     *无过期时间
     * @param key 缓存的键值
     * @param value 缓存的值
     */
    public <T> void setCacheObject(final Object key, final T value)
    {
        redisTemplate.opsForValue().set(key, value);

    }

    /**
     * 缓存基本对象 有过期时间
     * @param key
     * @param value
     * @param timeout
     * @param timeUnit
     */
    public  void setCacheObject( Object key, Object  value, Integer timeout, TimeUnit timeUnit)
    {
        redisTemplate.opsForValue().set(key, value,timeout,timeUnit);
    }

    /**
     * 获取单个缓存
     * @param key
     * @return
     */
    public <T> T getCacheObject(Object key){
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    /**
     * 清除单个缓存
     * @param key
     */
    public void removeCache(Object key){
        redisTemplate.delete(key);
    }

    public List<RedisModel> getAllCache(){
        List<RedisModel> list = new ArrayList<>();
        Set<String> keys = redisTemplate.keys("*");

        keys.forEach((t)->{
            Object value = getCacheObject(t);
            RedisModel redisModel = new RedisModel();
            redisModel.setKey(t);
            redisModel.setValue(value);
            list.add(redisModel);
        });
        return list;
    }
}
